package servlet;



import com.alibaba.fastjson.JSON;
import vo.ResultVO;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class BaseServlet extends HttpServlet {

    public ResultVO successJson(Object value) {
        ResultVO resultVo = new ResultVO();
        resultVo.setData(value);
        return resultVo;
    }

    public ResultVO successJson(Object value, int code, String msg) {
        ResultVO resultVo = new ResultVO();
        resultVo.setData(value);
        resultVo.setCode(code);
        resultVo.setMsg(msg);
        return resultVo;
    }

    public ResultVO successJson() {
        return new ResultVO();
    }

    public ResultVO errorJson() {
        ResultVO resultVo = new ResultVO();
        resultVo.setCode(500);
        resultVo.setMsg("系统繁忙，请稍后再试!");
        return resultVo;
    }

    public ResultVO errorJson(int code, String msg) {
        ResultVO resultVo = new ResultVO();
        resultVo.setCode(code);
        resultVo.setMsg(msg);
        return resultVo;
    }

    public ResultVO errorJson(String msg) {
        ResultVO resultVo = new ResultVO();
        resultVo.setCode(500);
        resultVo.setMsg(msg);
        return resultVo;
    }

    /**
     * 响应 JSON 字符串 到客户端浏览中
     * @param resp
     * @param resultVO 响应数据
     * @throws IOException
     */
    public void print(HttpServletResponse resp, ResultVO resultVO) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(resultVO));
        out.flush();
        out.close();
    }


}
